


import tracker from '../util/tracker';
import getLastEvent from '../util/getLastEvent';
import getSelector from '../util/getSelector';

export function injectJsError() {
    //监听全局未捕获的报错
    window.addEventListener('error',function(event){ 
        let lastEvent = getLastEvent(); //获取到最后一个交互事件
        // console.log(event);
        let log = {
            "kind": "stability",//大类
            "type": "error",//小类
            "errorType": "jsError",//错误类型
            // "url": event.filename,//访问哪个URL
            "message": event.message,//报错信息 
            "filename": event.filename,//访问的文件名
            "position": `${event.lineno}:${event.colno}`,//行列信息
            "stack": getLines(event.error.stack),//错误堆栈
            "selector": lastEvent ? getSelector(lastEvent.path):'' //选择器，代表最后一个操作的元素
        }
        tracker.send(log)
    })
    //当Promise 被 reject 且没有 reject 处理器的时候，会触发 unhandledrejection 事件
    window.addEventListener('unhandledrejection', (event)=>{
        console.log(event);
        let lastEvent = getLastEvent();
        let message = '';
        let line = 0;
        let column = 0;
        let file = '';
        let stack = '';


        let reason = event.reason;
        if (typeof reason === 'string') {
            message = reason;
        } else if (typeof reason === 'object') {
            if (reason.stack) {
                var matchResult = reason.stack.match(/at\s+(.+):(\d+):(\d+)/);
                if (matchResult) {
                    file = matchResult[1];
                    line = matchResult[2];
                    column = matchResult[3];
                }
                stack = getLines(reason.stack);
            }
            message = event.reason.message;
        }
        tracker.send({//未捕获的promise错误
            kind: 'stability',//稳定性指标
            type: 'error',//jsError
            errorType: 'promiseError',//unhandledrejection
            message,//标签名
            filename: file,
            position: line + ':' + column,//行列
            stack,
            selector: lastEvent ? getSelector(lastEvent.path ) : ''
        })
        
    },true)// true代表在捕获阶段调用,false代表在冒泡阶段捕获,使用true或false都可以
}



// 将堆栈信息格式化
function getLines(stack) {
    if (!stack) {
        return '';
    }
    return stack.split('\n').slice(1).map(item => item.replace(/^\s+at\s+/g, '')).join('^');
}